<?php
//require_once '../vendor/autoload.php';
use app\common\model\Category;
use fast\Form;
use fast\Tree;
use think\Db;
use think\Env;
use think\Loader;
use Google\Client;
use Google\Service\Vision;



if (!function_exists('build_select')) {

    /**
     * 生成下拉列表
     * @param string $name
     * @param mixed  $options
     * @param mixed  $selected
     * @param mixed  $attr
     * @return string
     */
    function build_select($name, $options, $selected = [], $attr = [])
    {
        $options = is_array($options) ? $options : explode(',', $options ?? '');
        $selected = is_array($selected) ? $selected : explode(',', $selected ?? '');
        return Form::select($name, $options, $selected, $attr);
    }
}

if (!function_exists('build_radios')) {

    /**
     * 生成单选按钮组
     * @param string $name
     * @param array  $list
     * @param mixed  $selected
     * @return string
     */
    function build_radios($name, $list = [], $selected = null)
    {
        $html = [];
        $selected = is_null($selected) ? key($list) : $selected;
        $selected = is_array($selected) ? $selected : explode(',', $selected);
        foreach ($list as $k => $v) {
            $html[] = sprintf(Form::label("{$name}-{$k}", "%s " . str_replace('%', '%%', $v)), Form::radio($name, $k, in_array($k, $selected), ['id' => "{$name}-{$k}"]));
        }
        return '<div class="radio">' . implode(' ', $html) . '</div>';
    }
}

if (!function_exists('build_checkboxs')) {

    /**
     * 生成复选按钮组
     * @param string $name
     * @param array  $list
     * @param mixed  $selected
     * @return string
     */
    function build_checkboxs($name, $list = [], $selected = null)
    {
        $html = [];
        $selected = is_null($selected) ? [] : $selected;
        $selected = is_array($selected) ? $selected : explode(',', $selected);
        foreach ($list as $k => $v) {
            $html[] = sprintf(Form::label("{$name}-{$k}", "%s " . str_replace('%', '%%', $v)), Form::checkbox($name, $k, in_array($k, $selected), ['id' => "{$name}-{$k}"]));
        }
        return '<div class="checkbox">' . implode(' ', $html) . '</div>';
    }
}


if (!function_exists('build_category_select')) {

    /**
     * 生成分类下拉列表框
     * @param string $name
     * @param string $type
     * @param mixed  $selected
     * @param array  $attr
     * @param array  $header
     * @return string
     */
    function build_category_select($name, $type, $selected = null, $attr = [], $header = [])
    {
        $tree = Tree::instance();
        $tree->init(Category::getCategoryArray($type), 'pid');
        $categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $categorydata = $header ? $header : [];
        foreach ($categorylist as $k => $v) {
            $categorydata[$v['id']] = $v['name'];
        }
        $attr = array_merge(['id' => "c-{$name}", 'class' => 'form-control selectpicker'], $attr);
        return build_select($name, $categorydata, $selected, $attr);
    }
}

if (!function_exists('build_toolbar')) {

    /**
     * 生成表格操作按钮栏
     * @param array $btns 按钮组
     * @param array $attr 按钮属性值
     * @return string
     */
    function build_toolbar($btns = null, $attr = [])
    {
        $auth = \app\admin\library\Auth::instance();
        $controller = str_replace('.', '/', Loader::parseName(request()->controller()));
        $btns = $btns ? $btns : ['refresh', 'add', 'edit', 'del', 'import'];
        $btns = is_array($btns) ? $btns : explode(',', $btns);
        $index = array_search('delete', $btns);
        if ($index !== false) {
            $btns[$index] = 'del';
        }
        $btnAttr = [
            'refresh' => ['javascript:;', 'btn btn-primary btn-refresh', 'fa fa-refresh', '', __('Refresh')],
            'add'     => ['javascript:;', 'btn btn-success btn-add', 'fa fa-plus', __('Add'), __('Add')],
            'edit'    => ['javascript:;', 'btn btn-success btn-edit btn-disabled disabled', 'fa fa-pencil', __('Edit'), __('Edit')],
            'del'     => ['javascript:;', 'btn btn-danger btn-del btn-disabled disabled', 'fa fa-trash', __('Delete'), __('Delete')],
            'import'  => ['javascript:;', 'btn btn-info btn-import', 'fa fa-upload', __('Import'), __('Import')],
        ];
        $btnAttr = array_merge($btnAttr, $attr);
        $html = [];
        foreach ($btns as $k => $v) {
            //如果未定义或没有权限
            if (!isset($btnAttr[$v]) || ($v !== 'refresh' && !$auth->check("{$controller}/{$v}", $auth->id))) {
                continue;
            }
            list($href, $class, $icon, $text, $title) = $btnAttr[$v];
            //$extend = $v == 'import' ? 'id="btn-import-file" data-url="ajax/upload" data-mimetype="csv,xls,xlsx" data-multiple="false"' : '';
            //$html[] = '<a href="' . $href . '" class="' . $class . '" title="' . $title . '" ' . $extend . '><i class="' . $icon . '"></i> ' . $text . '</a>';
            if ($v == 'import') {
                $template = str_replace('/', '_', $controller);
                $download = '';
                if (file_exists("./template/{$template}.xlsx")) {
                    $download .= "<li><a href=\"/template/{$template}.xlsx\" target=\"_blank\">XLSX模版</a></li>";
                }
                if (file_exists("./template/{$template}.xls")) {
                    $download .= "<li><a href=\"/template/{$template}.xls\" target=\"_blank\">XLS模版</a></li>";
                }
                if (file_exists("./template/{$template}.csv")) {
                    $download .= empty($download) ? '' : "<li class=\"divider\"></li>";
                    $download .= "<li><a href=\"/template/{$template}.csv\" target=\"_blank\">CSV模版</a></li>";
                }
                $download .= empty($download) ? '' : "\n                            ";
                if (!empty($download)) {
                    $html[] = <<<EOT
                        <div class="btn-group">
                            <button type="button" href="{$href}" class="btn btn-info btn-import" title="{$title}" id="btn-import-file" data-url="ajax/upload" data-mimetype="csv,xls,xlsx" data-multiple="false"><i class="{$icon}"></i> {$text}</button>
                            <button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown" title="下载批量导入模版">
                                <span class="caret"></span>
                                <span class="sr-only">Toggle Dropdown</span>
                            </button>
                            <ul class="dropdown-menu" role="menu">{$download}</ul>
                        </div>
EOT;
                } else {
                    $html[] = '<a href="' . $href . '" class="' . $class . '" title="' . $title . '" id="btn-import-file" data-url="ajax/upload" data-mimetype="csv,xls,xlsx" data-multiple="false"><i class="' . $icon . '"></i> ' . $text . '</a>';
                }
            } else {
                $html[] = '<a href="' . $href . '" class="' . $class . '" title="' . $title . '"><i class="' . $icon . '"></i> ' . $text . '</a>';
            }
        }
        return implode(' ', $html);
    }
}

if (!function_exists('build_heading')) {

    /**
     * 生成页面Heading
     *
     * @param string $path 指定的path
     * @return string
     */
    function build_heading($path = null, $container = true)
    {
        $title = $content = '';
        if (is_null($path)) {
            $action = request()->action();
            $controller = str_replace('.', '/', Loader::parseName(request()->controller()));
            $path = strtolower($controller . ($action && $action != 'index' ? '/' . $action : ''));
        }
        // 根据当前的URI自动匹配父节点的标题和备注
        $data = Db::name('auth_rule')->where('name', $path)->field('title,remark')->find();
        if ($data) {
            $title = __($data['title']);
            $content = __($data['remark']);
        }
        if (!$content) {
            return '';
        }
        $result = '<div class="panel-lead"><em>' . $title . '</em>' . $content . '</div>';
        if ($container) {
            $result = '<div class="panel-heading">' . $result . '</div>';
        }
        return $result;
    }
}

if (!function_exists('createImg')) {
    function createImg($sourcePath, $targetWidth, $targetHeight) {
        if(Env::get('img.baseurl')!="https://".$_SERVER["HTTP_HOST"]&&Env::get('img.baseurl')!="http://".$_SERVER["HTTP_HOST"]){
            $sourcePath= str_replace($_SERVER["DOCUMENT_ROOT"], '', $sourcePath);
            $sourcePath= Env::get('img.baseurl').str_replace("//", '/', $sourcePath);
            $sourcePath= preg_replace("/\.(jpg|jpeg|png|gif|jpeg)$/Uisx","_".$targetWidth."_".$targetHeight.".$1", $sourcePath);
            return $sourcePath;
        }
        
        // 检查源路径是否有效
        if (empty($sourcePath) || !is_string($sourcePath)) {
            return '';
        }
        
        // 生成新文件名
        $pathInfo = pathinfo($sourcePath);
        $extension = isset($pathInfo['extension']) ? strtolower($pathInfo['extension']) : 'jpg';
        $filename = isset($pathInfo['filename']) ? $pathInfo['filename'] : 'image';
        $dirname = isset($pathInfo['dirname']) ? $pathInfo['dirname'] : '';
        
        $newFileName = $filename . "_{$targetWidth}_{$targetHeight}." . $extension;
        $targetPath = $dirname . '/' . $newFileName;

        ini_set('memory_limit', '256M');

        // 检查文件是否已存在
        if (file_exists($targetPath)) {
            return path2url($targetPath); // 如果文件已存在，直接返回路径
        }

        // 确保 GD 库已安装
        if (!extension_loaded('gd')) {
            throw new Exception('GD 库未安装');
        }

        // 获取原图信息
        list($sourceWidth, $sourceHeight, $sourceType) = @getimagesize($sourcePath);

        // 确保目标宽高是整数
        $targetWidth = (int)$targetWidth;
        $targetHeight = (int)$targetHeight;

        // 根据文件类型创建图像资源
        switch ($sourceType) {
            case IMAGETYPE_JPEG:
                $sourceImage = imagecreatefromjpeg($sourcePath);
                $extension = 'jpg';
                break;
            case IMAGETYPE_PNG:
                $sourceImage = imagecreatefrompng($sourcePath);
                $extension = 'png';
                break;
            case IMAGETYPE_GIF:
                $sourceImage = imagecreatefromgif($sourcePath);
                $extension = 'gif';
                break;
            default:
                return $sourcePath; // 不支持的图像类型，直接返回原路径
        }

        // 创建最终的目标图像
        $targetImage = imagecreatetruecolor($targetWidth, $targetHeight);

        // 保持透明度（对于PNG和GIF）
        if ($sourceType == IMAGETYPE_PNG || $sourceType == IMAGETYPE_GIF) {
            imagealphablending($targetImage, false);
            imagesavealpha($targetImage, true);
            $transparent = imagecolorallocatealpha($targetImage, 255, 255, 255, 127);
            imagefilledrectangle($targetImage, 0, 0, $targetWidth, $targetHeight, $transparent);
        }

        // 计算缩放比例
        $sourceRatio = $sourceWidth / $sourceHeight;
        $targetRatio = $targetWidth / $targetHeight;

        if ($sourceRatio > $targetRatio) {
            // 原图更宽，应该裁剪宽度
            $newWidth = (int)($sourceHeight * $targetRatio);
            $newHeight = $sourceHeight;
            $sourceX = (int)(($sourceWidth - $newWidth) / 2);
            $sourceY = 0;
        } else {
            // 原图更高，应该裁剪高度
            $newWidth = $sourceWidth;
            $newHeight = (int)($sourceWidth / $targetRatio);
            $sourceX = 0;
            $sourceY = (int)(($sourceHeight - $newHeight) / 2);
        }

        // 直接从原图到目标图进行复制缩放，跳过中间裁剪步骤以避免黑边
        imagecopyresampled(
            $targetImage,       // 目标图像
            $sourceImage,       // 源图像
            0,                  // 目标图像的起始X坐标
            0,                  // 目标图像的起始Y坐标
            $sourceX,           // 源图像的起始X坐标
            $sourceY,           // 源图像的起始Y坐标
            $targetWidth,       // 目标图像的宽度
            $targetHeight,      // 目标图像的高度
            $newWidth,          // 源图像上需要复制的区域宽度
            $newHeight          // 源图像上需要复制的区域高度
        );

        // 保存图像
        switch ($extension) {
            case 'jpg':
                imagejpeg($targetImage, $targetPath, 90);
                break;
            case 'png':
                imagepng($targetImage, $targetPath, 9);
                break;
            case 'gif':
                imagegif($targetImage, $targetPath);
                break;
        }

        // 释放资源
        imagedestroy($sourceImage);
        imagedestroy($targetImage);

        return path2url($targetPath);
    }
}


if (!function_exists('path2url')) {
    function path2url($path)
    {
        $path = preg_replace('/^public/', '/public', $path);
        $path = str_replace('\\', '/', $path);
        $path = str_replace(str_replace('\\', '/', ROOT_PATH), '', $path);
        $path = str_replace('//', '/', $path);
        $path = preg_replace('/^public/', '', $path);
        $path = Env::get('img.baseurl').$path;
        return $path;
    }
}

function changeUrl($url){
    if(Env::get('img.baseurl')!="https://".$_SERVER["HTTP_HOST"]&&Env::get('img.baseurl')!="http://".$_SERVER["HTTP_HOST"]){
        return $url;
    }
    return Env::get('img.baseurl').$url;
}

